from django.db.models import Q
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView, CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from apps.headlines.models import Channel, Article, Comment
from apps.headlines.serializers import PagNun, LabelsInfoSerializer, ChannelsGroupSerializer, ChannelInfoSerializer, \
    AddArticleSerializer, ArticleSerializer, PublishCommentSerializer
from apps.questions.models import Label
from apps.users.models import User
from tentimes.utils.qiniuyun import img_upload

from apps.headlines.serializers import ArticleInfoSerializer


class ChannelsGroupView(ListAPIView):
    queryset = Channel.objects.all()
    serializer_class = ChannelsGroupSerializer
    pagination_class = PagNun


# 根据关键字搜索文章
class PublishSerchView(ListAPIView):
    queryset = Article.objects.all()
    serializer_class = ChannelInfoSerializer
    pagination_class = PagNun

    def get_queryset(self):
        keyword = self.request.query_params.get('text')
        if keyword:
            return Article.objects.filter(Q(title__contains=keyword) | Q(content__contains=keyword))
        else:
            return Article.objects.all()


# 上传图片
class UploadAvatarView(CreateAPIView):
    queryset = Article.objects.all()
    serializer_class = AddArticleSerializer

    def create(self, request, *args, **kwargs):
        # 七牛云
        data = request.FILES.get('img')
        img_url = img_upload(data)
        print(img_url)
        return Response(
            {
                'imgurl': img_url
            },
        )
        # fistDFS
        # # 创建客户端对象:
        # client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        # data = request.FILES.get('img')
        # # 上传图片到fastDFS
        # res = client.upload_by_buffer(data.read())
        # # 判断是否上传成功
        # if res['Status'] != 'Upload successed.':
        #     return Response(status=403)
        # # 获取上传后的路径
        # image_url = settings.FDFS_URL + res['Remote file_id']
        # # print(type(image_url))
        # return Response(
        #     {
        #         'imgurl': image_url
        #     },
        # )


# 获取标签
class LabelsInfoView(ListAPIView):
    queryset = Label.objects.all()
    serializer_class = LabelsInfoSerializer


# 文章相关视图
class AddArticleView(ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    pagination_class = PagNun

    # 发布文章
    def create(self, request, *args, **kwargs):
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            request_params = request.data
            # image = request_params.pop('image')
            request_params['user'] = user.id
            serializer = AddArticleSerializer(data=request_params)
            serializer.is_valid(raise_exception=True)
            data = serializer.validated_data
            labels = data.pop('labels')
            article = Article.objects.create(**data)
            article.labels.add(*labels)
            article.save()

            return Response({'success': True, 'message': '发表成功', 'articleid': article.id})
        else:
            return Response({'success': False, 'message': '未登录'}, status=status.HTTP_400_BAD_REQUEST)

    # 文章列表
    @action(methods=['get'], detail=True, url_path="channel")
    def get_channel_list(self, request, pk):
        if pk == '-1':
            articles = self.get_queryset()
        else:
            channel = Channel.objects.get(id=pk)
            articles = self.get_queryset().filter(channel=channel)
        page = self.paginate_queryset(articles)
        s = ChannelInfoSerializer(page, many=True)
        return self.get_paginated_response(s.data)

    def channelinfo(self, request, pk):
        channe_id = int(self.kwargs['pk'])
        article = Article.objects.get(id=channe_id)
        serializer = AddArticleSerializer(article)
        return Response(serializer.data)

    # 文章收藏
    @action(methods=['put'], detail=True)
    def collect(self, request, pk):

        article = Article.objects.get(id=int(pk))
        if request.user.collected_articles.filter(id=int(pk)):
            request.user.collected_articles.remove(article)
            return Response({'success': True, 'message': '取消收藏成功'})
        else:

            request.user.collected_articles.add(article)
            return Response({'success': True, 'message': '收藏成功'})


# 获取文章详情
# class ArticleInfoView(ListAPIView):
#     queryset = Article.objects.all()
#     serializer_class = ArticleInfoSerializer
#
#     def list(self, request, *args, **kwargs):
#         id = int(self.kwargs['pk'])
#         article = Article.objects.get(id=id)
#         serializer = ArticleInfoSerializer(article)
#
#         return Response(serializer.data)
class ArticleInfoView(APIView):
    def get(self,requset,pk):
        try:
           article = Article.objects.get(id=pk)
        except Article.DoesNotExist:
            return Response(status.HTTP_400_BAD_REQUEST)
        article.visits +=1
        article.save()
        serializer = ArticleInfoSerializer(article)
        return Response(serializer.data)

# 评论
# class PublishCommentView(CreateAPIView):
#     queryset = Article.objects.all()
#     serializer_class = PublishCommentSerializer
#
#     def create(self, request, *args, **kwargs):
#         user = request.user
#         article_id = request.data.get('article')
#         content = request.data.get('content')
#         # request_params['user'] = userid
#         Comment.objects.create(article_id=article_id, user=user, content=content)
#
#         article = Article.objects.get(id=article_id)
#         article.comment_count += 1
#         article.save()
#
#         return Response({'success': True, 'message': '评论成功'})

class PublishCommentView(APIView):
    def post(self,request,pk):
        article = request.data.get("article")
        content = request.data.get("content")
        parent = request.data.get("parent")
        user = request.user
        if not parent:
            try:
                article = Article.objects.get(id=article)
            except Article.DoesNotExist:
                return Response(status.HTTP_400_BAD_REQUEST)
            Comment.objects.create(article=article, user=user, content=content)
            article.comment_count += 1
            article.save()
        else:
            try:
                parent_comment = Comment.objects.get(id=parent)
                article = Article.objects.get(id=article)
            except Comment.DoesNotExist:
                return Response(status.HTTP_400_BAD_REQUEST)
            comment = Comment.objects.create(article=article, user=user, content=content,parent=parent_comment)
        return Response({'success': True, 'message': '评论成功'})
# 关注
class UserLikeView(APIView):

    def post(self, request, pk):
        my_user = request.user
        fans_user = User.objects.get(id=pk)
        my_user.fans.add(fans_user)
        return Response({
            'success': True,
            'message': '关注成功'
        })

    def delete(self, request, pk):
        my_user = request.user
        fans_user = User.objects.get(id=pk)
        my_user.fans.remove(fans_user)
        return Response({
            'success': True,
            'message': '取消关注'
        })
